from google.appengine.api import urlfetch
import BeautifulSoup

import geo

DEFAULT_MAX_ROUTE_LENGTH = 20

class Blog(object):
    def __init__(self, feed_url):
        self.feed_url = feed_url
        self.__fix = None
        self.__feed = None
        
    @property
    def feed(self):
        if not self.__feed:
            response = urlfetch.fetch(self.feed_url)
            if response.status_code != 200: return None
            self.__feed = BeautifulSoup.BeautifulSoup(response.content)
        return self.__feed
        
    def __get_location_fix(self):
        points = self.feed("georss:point", limit=1)
        if not points: 
            return
        else:
            latitude, longitude = points[0].text.split()
        self.__fix = geo.Point(latitude, longitude)
    
    @property
    def fix(self):
        if not self.__fix:
            self.__get_location_fix()
        return self.__fix
    
    def get_route(self, max_length=DEFAULT_MAX_ROUTE_LENGTH):
        points = self.feed("georss:point", limit=max_length)
        if not points:
            return None
        route = []
        for point in reversed(points):
            route.append(geo.Point(*point.text.split()))
        return route